package com.mystudyspring.studySpringBoot.controller;

import com.mystudyspring.studySpringBoot.dao.UserRepository;
import com.mystudyspring.studySpringBoot.domain.ApiResultDto;
import com.mystudyspring.studySpringBoot.domain.User;
import com.mystudyspring.studySpringBoot.dto.UserDto;
import com.mystudyspring.studySpringBoot.util.LoggerUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 用户控制器
 *
 * @author lix
 * @create 2018-03-22 11:06
 */
@Api(value = "Swagger动态文档demo", description = "this is desc", position = 100, protocols = "http")
@RestController
@RequestMapping(value = "/users")
public class UserController {

    private final static Logger logger = LoggerFactory.getLogger(UserController.class);
    static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());

    @Autowired
    private UserRepository userRepository;

    @ApiOperation(value = "获取用户列表", notes = "")
    @RequestMapping(value = "/getlist", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public List<User> getUserList(HttpServletRequest request) {
        List<User> list = userRepository.findAll();
        request.setAttribute(LoggerUtils.LOGGER_RETURN, list);
        return list;
    }

    @ApiOperation(value = "adduserfor", notes = "")
    @RequestMapping(value = "/adduserfor", method = RequestMethod.POST)
    public ApiResultDto AddUserFor(@ModelAttribute User user, HttpServletRequest request) {

        User u = userRepository.save(user);

        ApiResultDto resp = ApiResultDto.newInstance();
        resp.setMsg("success");
        resp.setResult(u);
        request.setAttribute(LoggerUtils.LOGGER_RETURN, resp);
        return resp;
    }

    @ApiOperation(value = "post添加用户", notes = "根据User对象创建用户")
    @RequestMapping(value = "/adduser", method = RequestMethod.POST)
    public String AddUser(@RequestBody UserDto userDto) {
        User u = userRepository.save(new User(userDto.getName(),userDto.getAge()));
        return "success";
    }
}

